package day4

import (
	"fmt"
	"strconv"
	"sync"
)

/*
互斥锁, var mu sync.Mutex 读和写频率一样的场景
读写锁, var mu sync.RWMutex 读多写少的场景
 */

var hLock sync.Mutex
var rwLock sync.RWMutex

func Lockh(){
	//runTest1()
	runTest2()
}

func runTest1(){
	ch := make(chan int)
	for i := 0; i < 10; i++ {
		go test(ch, i)
	}
	for i := 0; i < 10; i++ {
		<-ch
	}
}

func test(ch chan int, i int) {
	hLock.Lock()
	fmt.Println(i)
	ch <- i
	hLock.Unlock()
}

func runTest2(){
	mapa := map[int]string{1: "world"}

	//写
	for i := 1; i < 10; i ++{
		go write(mapa,i)
	}

	//读
	for i := 1; i < 10; i ++{
		go read(mapa,i)
	}
}

func read(mapa map[int]string, i int) {
	rwLock.RLock()
	fmt.Println(mapa[i])
	rwLock.RUnlock()
}

func write(mapa map[int]string, i int) {
	rwLock.Lock()
	mapa[i] = strconv.Itoa(i) + "666"
	rwLock.Unlock()
}